﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;

namespace Framework.WebmasterTool.Logs
{
    public partial class Default : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        public string GridViewSortExpression
        {
            get { return ViewState["GridViewSortExpression"] == null ? "ActionedDate" : ViewState["GridViewSortExpression"] as string; }
            set { ViewState["GridViewSortExpression"] = value; }
        }

        public SortDirection GridViewSortOrder
        {
            get { return ViewState["GridViewSortOrder"] == null ? SortDirection.Descending : (SortDirection)ViewState["GridViewSortOrder"]; }
            set { ViewState["GridViewSortOrder"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                LoadCateDDL();
                LoadLogs();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.LogSystem.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void LoadCateDDL()
        {
            List<string> usersActioned = entity.udv_Log.GroupBy(ua => ua.ActionBy).Select(ua => ua.Key).ToList();
            ddlUsers.DataSource = usersActioned;
            ddlUsers.DataBind();
        }

        public void LoadLogs()
        {
            var logs = entity.udv_Log.Select(lg => new { lg.LogID, lg.Title, lg.IpAdress, lg.ActionedDate, lg.ActionBy })
                .OrderByDescending(lg => lg.ActionedDate).ToList();
            grvLogs.DataSource = logs;
            grvLogs.DataBind();
        }

        protected void grvLogs_Sorting(object sender, GridViewSortEventArgs e)
        {
            //Check if the same column is sorted to switch Sort Order  
            if (GridViewSortExpression.Equals(e.SortExpression))
                GridViewSortOrder = GridViewSortOrder.Equals(SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
            else
                GridViewSortOrder = SortDirection.Ascending;
            //save Sort Expression and Sort Order
            GridViewSortExpression = e.SortExpression;
            if (grvLogs.ToolTip == "all")
                LoadLogs();
            else
            {
                SearchLogs();
            }
        }

        protected void grvLogs_DataBinding(object sender, EventArgs e)
        {
            string srcImageASC = Globals.ApplicationPath + "WebmasterTool/Images/ASC.gif";
            string srcImageDESC = Globals.ApplicationPath + "WebmasterTool/Images/DESC.gif";
            foreach (DataControlField column in grvLogs.Columns)
            {
                //Remove Previous Sort Image  
                column.HeaderText = Regex.Replace(column.HeaderText, "<[^>]*>", "", RegexOptions.IgnoreCase);
                if (column.SortExpression.Equals(GridViewSortExpression))
                {
                    //set new sort image  
                    string strSortImageURL = GridViewSortOrder == SortDirection.Descending ?
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageDESC + "' />" :
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageASC + "' />";
                    column.HeaderText = String.Format("{0}{1}", column.HeaderText, strSortImageURL);
                }
            }
        }

        protected void grvLogs_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvLogs.PageIndex = e.NewPageIndex;
            if (grvLogs.ToolTip == "all")
                LoadLogs();
            else
            {
                SearchLogs();
            }
        }

        public void SearchLogs()
        {
            var logs = entity.udv_Log.Select(lg => new { lg.LogID, lg.Title, lg.IpAdress, lg.ActionedDate, lg.ActionBy }).ToList();

            if (!string.IsNullOrEmpty(txtKeyword.Text.Trim()))
            {
                string keywords = Globals.RemoveSign4VietnameseString(txtKeyword.Text.Trim());
                logs = logs.Where(lg => Globals.RemoveSign4VietnameseString(lg.Title.ToLower()).Contains(keywords.ToLower())).ToList();
            }
            if (ddlUsers.SelectedValue != "0")
            {
                string userActioned = ddlUsers.SelectedValue;
                logs = logs.Where(lg => lg.ActionBy == userActioned).ToList();
            }
            if (!string.IsNullOrEmpty(txtFomDate.Text.Trim()))
            {
                DateTime dateFrom = DateTime.Parse(txtFomDate.Text.Trim());
                logs = logs.Where(lg => lg.ActionedDate >= dateFrom).ToList();
            }
            if (!string.IsNullOrEmpty(txtToDate.Text.Trim()))
            {
                DateTime dateTo = DateTime.Parse(txtToDate.Text.Trim());
                logs = logs.Where(lg => lg.ActionedDate <= dateTo).ToList();
            }

            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                logs = logs.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                logs = logs.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();

            grvLogs.DataSource = logs;
            grvLogs.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            grvLogs.PageIndex = 0;
            grvLogs.ToolTip = "search";
            SearchLogs();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in grvLogs.Rows)
            {
                bool isChecked = ((HtmlInputCheckBox)row.FindControl("chkSelect")).Checked;
                if (isChecked)
                {
                    int logID = int.Parse(((HtmlInputCheckBox)row.FindControl("chkSelect")).Attributes["title"].Trim());
                    udv_Log LogDelete = entity.udv_Log.Where(lg => lg.LogID == logID).FirstOrDefault();
                    if (LogDelete != null)
                    {
                        //create db log
                        CreateDBLog(null, null, TypeAction.Delete, "Xoá log hệ thống: " + LogDelete.Title, "", "", "", "",
                            "", "", "", "");

                        entity.DeleteObject(LogDelete);
                        entity.SaveChanges();
                    }
                }
            }

            if (grvLogs.ToolTip == "all")
                LoadLogs();
            else
            {
                SearchLogs();
            }
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
            string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}